package com.ksyun.ks3.services.request;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

public class InputStreamRequestBody extends RequestBody {

    private String contentType;
    private InputStream is;
    private long length;

    public InputStreamRequestBody (InputStream is, String contentType, long contentLength) {
        this.is = is;
        this.contentType = contentType;
        this.length = contentLength;
    }

    @Override
    public MediaType contentType() {
        if (null != this.contentType) return MediaType.parse(this.contentType);
        return null;
    }

    @Override
    public long contentLength() throws IOException {
        if (0 != length) return length;
        return -1;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if (null == is) return;
        try {
            Source source = Okio.source(is);
            sink.writeAll(source);
        } catch (IOException e) {
            throw e;
        }
    }
}
